from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import load_model

def image_to_number(n):

    fig, ax = plt.subplots(nrows=int(n/5),ncols=5 )
    ax = ax.flatten()
    image_test = []
    label_test = np.zeros((n,10))#手写图片的lebel
    for i in range(n):
        label_test[i][i] =1#将（0,0）（1,1）等位置赋值为1
        imag1 = [1]
        imag28 = [imag1] * 28
        line = [imag28] * 28


        line = np.array(line)
        # print(L.shape)
        img = Image.open("{}.png".format(i))     # 打开一个图片，并返回图片对象
        img = img.convert('L')    # 转换为灰度，img.show()可查看图片
        # print(img.size)
        img = img.resize((28, 28))   # 将图片重新以（w,h）尺寸存储
        for y in range(28):
            for x in range(28):
                line[y][x][0]=((255-img.getpixel((x, y)))/255)# getpixel 获取该位置的像素信息

        image_test.append(line)#存储像素点信息


        line = np.array(line)#转化为np.array

        ax[i].imshow(line.reshape(28,28), cmap='Greys', interpolation='nearest')
        # plt.imshow(line.reshape(28,28), cmap='Greys')#显示图片，imshow能够将数字转换为灰度显示出图像

    plt.show()
    image_test = np.array(image_test)
    # print(image_test.shape)

    return image_test

if __name__ == '__main__':
    model = load_model("C:\\Users\\李子珩\\PycharmProjects\\chuangxinshijian\\save3.h5")
    pre_x = image_to_number(10)
    pre_y = model.predict(pre_x)
    result_max = np.argmax(pre_y, axis=1)  # axis=1表示按行 取最大值   如果axis=0表示按列 取最大值 axis=None表示全部

    print(result_max)
